require 'rubygems' # Unless you install from the tarball or zip.
require 'icalendar'
require 'date'


include Icalendar

class EndarEventController < ApplicationController
	layout 'standard' 

  $utc_flag = 1
  
	def new
		@event = EndarEvent.new
		@event.endar_event_times.build
		
		#Email users link to events/show/id --not quite doing link yet
		
	end
	
	def create_xml
		event_obj = params[:event]
		
		#if not event_obj.nil?
		#	if event_obj[:name].nil? || event_obj[:date_end].nil?
		#		render :text => "error"
		#		return
		#	end
			
		#end	
		
		@event = EndarEvent.new
		#@event.date_begin 	= DateTime.strptime(event_obj[:date_begin], "%Y/%m/%d %H:%M:%S").to_time
		#@event.date_end 	= DateTime.strptime(event_obj[:date_end], "%Y/%m/%d %H:%M:%S").to_time
		@event.name			= event_obj[:name]
		@event.description 	= event_obj[:description]
		@event.duration		= event_obj[:duration].to_i
		@event.admin		= "whatever"
		timeBegin = DateTime.strptime(event_obj[:time_start], "%H:%M:%S").to_time
		timeEnd = DateTime.strptime(event_obj[:time_end], "%H:%M:%S").to_time		
		
		date_array = []
		#date MMDDYYYY separated by ','
		date_string = event_obj[:date_string]
		#extract dates from date_string
		dates = date_string.split(',')		
		
		#puts dates
		
		dates.each do |date|
			
			# puts 'date'
			# puts date			
			
			@this_day = DateTime.strptime(date, "%m/%d/%Y").to_time
			
			puts 'this_day ------------------------------------------------------------'
			puts @this_day
			
			# puts 'timeEnd'
			# puts timeEnd
			
			# puts 'timeBegin'
			# puts timeBegin
			
			
			
			
			while (timeEnd.hour() * 60) + timeEnd.min() - (timeBegin.hour() * 60) - timeBegin.min() > 0
				#puts '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~`'
				puts 'timeBegin + timeEnd'
				puts timeBegin
				puts timeEnd
				
				@this_new_day = @this_day.advance(:hours => timeBegin.hour()).advance(:minutes => timeBegin.min())
				
				
				@event.endar_event_times.build(:date_begin => @this_new_day, :date_end => @this_new_day.advance(:minutes => 30), :count => 0, :event_id => 0)
				timeBegin = @this_new_day.advance(:minutes => 30)
			end
			timeBegin = DateTime.strptime(event_obj[:time_start], "%H:%M:%S").to_time
		end		
		
		puts "DATE BEGIN OF EVENT:" + @event.date_begin.to_s()
		#t.strftime("at %I:%M%p")            #=> "at 08:56AM"
		#  %I - Hour of the day, 12-hour clock (01..12)
		#%M - Minute of the hour (00..59)
		#%p - Meridian indicator (``AM''  or  ``PM'')
		#%S - Second of the minute (00..60)
		#puts "event_obj[time_begin]: " 
		#puts event_obj[:time_begin]
		
		#@event = EndarEvent.new(params[:event])
		if @event.duration % 30 != 0
			@event.duration = @event.duration + 30 - (@event.duration % 30)
		end
		
		if @event.save			
			 @event.endar_event_times.each do |event_time|
				event_time.update_attributes("event_id" => @event.id)
			 end					
			
			@event.update_attributes("date_begin" => EndarEventTime.find(:first, :order =>  'date_begin ASC', :conditions => ["event_id = ?", @event.id]).date_begin)
			@event.update_attributes("date_end" => EndarEventTime.find(:last, :order => 'date_end ASC', :conditions => ["event_id = ?", @event.id]).date_end)
			@users = EndarUser.find(:all, :conditions => ["event_id = ?", @event.id])			
			#render :xml => @event.to_xml(:dasherize => false)			
			#render :xml => @users.to_xml(:dasherize => false)
			
			hash = {}
			hash["id"] = @event.id.to_s
			
			render :xml => hash.to_xml(:dasherize => false)
			
		else
			render :text => "error"
		end	
	end
	
	
	def create
		
		@event = EndarEvent.new(params[:event])
		if @event.duration % 30 != 0
			@event.duration = @event.duration + 30 - (@event.duration % 30)
		end
		
		params[:event_times].each_value do |event_time|
			e = EndarEventTime.new(event_time)
			beginMins = e.date_begin.min()
			endMins = e.date_end.min()
			
			puts ''
			puts e.date_begin
			puts e.date_end
			if beginMins % 30 != 0
				e.date_begin = e.date_begin.advance(:minutes => (30-(beginMins % 30)))
			end
			if endMins % 30 != 0
				e.date_end = e.date_end.advance(:minutes => -(endMins % 30))
			end
			while e.date_end - e.date_begin >= (60 * 30)
				@new_event_time = @event.endar_event_times.build(:date_begin => e.date_begin, :date_end => e.date_begin.advance(:minutes => 30), :count => 0, :event_id => 0)
				e.date_begin = @new_event_time.date_end
			end
		end
		
		if @event.save
			@event.endar_event_times.each do |event_time|
				event_time.update_attributes("event_id" => @event.id)
			end
			@event.update_attributes("date_begin" => EndarEventTime.find(:first, :order =>  'date_begin ASC', :conditions => ["event_id = ?", @event.id]).date_begin)
			@event.update_attributes("date_end" => EndarEventTime.find(:last, :order => 'date_end ASC', :conditions => ["event_id = ?", @event.id]).date_end)
			@users = EndarUser.find(:all, :conditions => ["event_id = ?", @event.id])
			flash[:notice] = 'Event Saved'
		else
			render :controller => 'endar_event', :action => 'new', :x => params[:x].to_i
		end
	
	end
	
	def email
	
		@id = params[:eid]
	
		# @event = EndarEvent.new(params[:event])
		# if @event.duration % 30 != 0
			# @event.duration = @event.duration + 30 - (@event.duration % 30)
		# end
		# params[:event_times].each_value do |event_time|
			# e = EndarEventTime.new(event_time)
			# beginMins = e.date_begin.min()
			# endMins = e.date_end.min()
			
			# puts ''
			# puts e.date_begin
			# puts e.date_end
			
			
			# if beginMins % 30 != 0
				# e.date_begin = e.date_begin.advance(:minutes => (30-(beginMins % 30)))
			# end
			# if endMins % 30 != 0
				# e.date_end = e.date_end.advance(:minutes => -(endMins % 30))
			# end
			
			
			# puts ''
			# puts e.date_begin
			# puts e.date_end
			# puts 'diff'
			# puts (e.date_end - e.date_begin)
			
			# while e.date_end - e.date_begin >= (60 * 30)
				# @new_event_time = @event.endar_event_times.build(:date_begin => e.date_begin, :date_end => e.date_begin.advance(:minutes => 30), :count => 0, :event_id => 0)
				# e.date_begin = @new_event_time.date_end
			# end
		# end
		
		# if @event.save
			# @event.endar_event_times.each do |event_time|
				# event_time.update_attributes("event_id" => @event.id)
			# end
			# @event.update_attributes("date_begin" => EndarEventTime.find(:first, :order =>  'date_begin ASC', :conditions => ["event_id = ?", @event.id]).date_begin)
			# @event.update_attributes("date_end" => EndarEventTime.find(:last, :order => 'date_end ASC', :conditions => ["event_id = ?", @event.id]).date_end)
			# @users = EndarUser.find(:all, :conditions => ["event_id = ?", @event.id])
		# else
			# render :controller => 'endar_event', :action => 'new', :x => params[:x].to_i
		# end


	end
	
	def emails_sent
		@event = EndarEvent.find(params[:id])
		#@event = EndarEvent.find(params[:event])
		#@event = params[:event]
		
		puts 'event id'
		puts @event.id
		
		adminEmail = params[:adminEmail]
		@admin = EndarUser.create(:name=>adminEmail, :event_id=>@event.id)
		
		puts 'admin'
		puts @admin.id
		
		@event.admin = adminEmail
		@event.save
		InviteUsers.deliver_link(adminEmail, @admin, @event)
	
	
		@recipients = params[:recipients]
		
		puts 'recipients'
		puts @recipients
		
		if not @recipients.nil?		
			@recArray = @recipients.split(',')
			@recArray.each do |recipient|
				@user = EndarUser.create(:name=>recipient, :event_id=>@event.id)
				InviteUsers.deliver_invite(recipient, @user, @event)
			end
		end
	end
	
	def list_xml
		#@user = EndarUser.find(:all, :conditions => ["event_id = ?", params[:id]])		
		#render :xml => EndarUser.find(:all, :conditions => ["event_id = ?", params[:id]]).to_xml(:dasherize => false)
		#@user = EndarUser.find(:all, :conditions => ["event_id = ?", params[:eventID]])	
		@user = EndarUser.find(:all, :conditions => ["event_id = ?", session[:eventID]])
		render :xml => @user.to_xml(:dasherize => false)	
			
	end
	
	def get_best_time_xml		
		if session[:best].nil? || session[:best].first[:date_begin].nil? || session[:best].first[:date_end].nil?
			render :text => "error"				
		else		
			@best_date_begin = session[:best].first[:date_begin]
			@best_date_end = session[:best].first[:date_end]
			@eventName = session[:eventName]
			@eventDescription = session[:eventDescription]
			
			@eStartYear = @best_date_begin.year
			@eStartMonth = @best_date_begin.month
			@eStartDay = @best_date_begin.day
			@eStartHour = @best_date_begin.hour
			@eStartMinute = @best_date_begin.min
			
			@eEndYear = @best_date_end.year
			@eEndMonth = @best_date_end.month
			@eEndDay = @best_date_end.day
			@eEndHour = @best_date_end.hour
			@eEndMinute = @best_date_end.min			
			
			best_obj = {}
			
			if (@eStartHour < 12)
				mode = "AM"
			else
				if (@eStartHour == 12 && @eStartMinute == 0)
					mode = "AM"
				else mode = "PM"
				end				
			end
			
			if @eStartMonth < 10
				startmonth = '0' + @eStartMonth.to_s
			else
				startmonth = '' + @eStartMonth.to_s
			end
			
			if @eStartDay < 10
				startday = '0' + @eStartDay.to_s
			else
				startday = '' + @eStartDay.to_s
			end
			
			if @eStartHour < 10
				starthour = '0' + @eStartHour.to_s
			else
				starthour = '' + @eStartHour.to_s
			end
			
			if @eStartMinute < 10
				startmin = '0' + @eStartMinute.to_s
			else
				startmin = '' + @eStartMinute.to_s
			end			
			
			
			#best_obj["dtstart"] = startmonth+"/"+startday+"/"+ @eStartYear.to_s + ' ' +starthour+":"+startmin+":"+"0 "+mode		
			best_obj["dtstart"] = @eStartMonth.to_s+"/"+@eStartDay.to_s+"/"+ @eStartYear.to_s + ' ' +@eStartHour.to_s+":"+@eStartMinute.to_s+":"+"0 "+mode		
			best_obj["dtstart1"] = @eStartYear.to_s + startmonth + startday + "T" + starthour + startmin + "00"
			best_obj["dtstart2"] = startmonth+"/"+startday+"/"+ @eStartYear.to_s
			
			if @eEndMonth < 10
				endmonth = '0' + @eEndMonth.to_s
			else
				endmonth = '' + @eEndMonth.to_s
			end
			
			if @eEndDay < 10
				endday = '0' + @eEndDay.to_s
			else
				endday = '' + @eEndDay.to_s
			end
			
			if @eEndHour < 10
				endhour = '0' + @eEndHour.to_s
			else
				endhour = '' + @eEndHour.to_s
			end
			
			if @eEndMinute < 10
				endmin = '0' + @eEndMinute.to_s
			else
				endmin = '' + @eEndMinute.to_s
			end
			
			if (@eEndHour < 12)
				mode = "AM"
			else
				if (@eEndHour == 12 && @eEndMinute == 0)
					mode = "AM"
				else mode = "PM"
				end				
			end
			
			best_obj["dtend"] = @eEndMonth.to_s+"/"+@eEndDay.to_s+"/"+ @eEndYear.to_s + ' ' +@eEndHour.to_s+":"+@eEndMinute.to_s+":"+"0 "+mode		
			best_obj["dtend1"] = @eEndYear.to_s + endmonth + endday + "T" + endhour + endmin + "00"
			best_obj["dtend2"] = endmonth+"/"+endday+"/"+ @eEndYear.to_s
			
			
			best_obj["summary"] = "BEST TIME: " + @eventDescription
			best_obj["description"] = @eventDescription
			render :xml => best_obj.to_xml
		end		
	
	end	
	
	def list_all_event_times_xml
		#@event = EndarEvent.find(params[:id])
		#@eID = session[:eID]
		@event_times = EndarEventTime.find(:all, :conditions => ["event_id = ?", session[:eventID]])	
		
		@blocks = Array.new
		@event_times.each do |event_time|
			@date_begin = event_time[:date_begin]
			@date_end = event_time[:date_end]
			#@eventName = session[:eventName]
			#@eventDescription = session[:eventDescription]
			@eStartYear = @date_begin.year
			@eStartMonth = @date_begin.month
			@eStartDay = @date_begin.day
			@eStartHour = @date_begin.hour
			@eStartMinute = @date_begin.min
			
			@eEndYear = @date_end.year
			@eEndMonth = @date_end.month
			@eEndDay = @date_end.day
			@eEndHour = @date_end.hour
			@eEndMinute = @date_end.min
			
			
			date_obj = {}
			
			if @eStartMonth < 10
				startmonth = '0' + @eStartMonth.to_s
			else
				startmonth = '' + @eStartMonth.to_s
			end
			
			if @eStartDay < 10
				startday = '0' + @eStartDay.to_s
			else
				startday = '' + @eStartDay.to_s
			end
			
			if @eStartHour < 10
				starthour = '0' + @eStartHour.to_s
			else
				starthour = '' + @eStartHour.to_s
			end
			
			if @eStartMinute < 10
				startmin = '0' + @eStartMinute.to_s
			else
				startmin = '' + @eStartMinute.to_s
			end
					
			date_obj["dtstart"] = @eStartYear.to_s + startmonth + startday + "T" + starthour + startmin + "00"
			
			
			if @eEndMonth < 10
				endmonth = '0' + @eEndMonth.to_s
			else
				endmonth = '' + @eEndMonth.to_s
			end
			
			if @eEndDay < 10
				endday = '0' + @eEndDay.to_s
			else
				endday = '' + @eEndDay.to_s
			end
			
			if @eEndHour < 10
				endhour = '0' + @eEndHour.to_s
			else
				endhour = '' + @eEndHour.to_s
			end
			
			if @eEndMinute < 10
				endmin = '0' + @eEndMinute.to_s
			else
				endmin = '' + @eEndMinute.to_s
			end
			
			date_obj["dtend"] = @eEndYear.to_s + endmonth + endday + "T" + endhour + endmin + "00"
			date_obj["summary"] = "[ " + event_time[:count].to_s() + " ]" #number of participants
			date_obj["description"] = "Participants: " + event_time[:count].to_s() #number of participants
			
			
			@blocks.insert(-1, date_obj)
		end
		
		render :xml => @blocks.to_xml(:dasherize => false)
					
	end
	
	
	
	def add_event_time
		@event_time = EndarEventTime.new
	end
	
	def create_best_ics
		
		@best_date_begin = session[:best].first[:date_begin]
		@best_date_end = session[:best].first[:date_end]
		@eventName = session[:eventName]
		@eventDescription = session[:eventDescription]
		cal = Calendar.new

		event = Event.new
		
		@eStartYear = @best_date_begin.year
		@eStartMonth = @best_date_begin.month
		@eStartDay = @best_date_begin.day
		@eStartHour = @best_date_begin.hour
		@eStartMinute = @best_date_begin.min
		event.start = DateTime.civil(@eStartYear, @eStartMonth, @eStartDay, @eStartHour, @eStartMinute).advance(:hours => 7)
		event.start.advance(:hours => 7)
		
		@eEndYear = @best_date_end.year
		@eEndMonth = @best_date_end.month
		@eEndDay = @best_date_end.day
		@eEndHour = @best_date_end.hour
		@eEndMinute = @best_date_end.min
		event.end = DateTime.civil(@eEndYear, @eEndMonth, @eEndDay, @eEndHour, @eEndMinute).advance(:hours => 7)
		
		event.summary = @eventName
		event.description = @eventDescription
		cal.add_event(event)
		
		response.content_type = Mime::ICS
		render :text=>cal.to_ical
	

	end

	
	
	def show
		@event = EndarEvent.find(params[:id])
		session[:eventName] = @event.name
		session[:eventDescription] = @event.description
		session[:eventID] = @event.id
		@users = EndarUser.find(:all, :conditions => ["event_id = ?", @event.id])
		@not_responded = Array.new  #array of users who have not responded
		@responded = Array.new
		@users.each do |user|
			@user_time = EndarUserTime.find(:first, :conditions => ["user_id = ?", user.id])
			if @user_time == nil
				@not_responded.insert(-1, user)
			else
				@responded.insert(-1, user)
			end
		end
		@event_times = EndarEventTime.find(:all, :order => 'date_begin ASC', :conditions => ["event_id = ?", @event.id])
		
		#add all the is_frees for all users of event for each event_time.date_begin (since those are unique now) to form a master count for each time slot
		@event_times.each do |e|
			e[:count] = 0
			@users.each do |u|
				@this_user = EndarUserTime.find(:first, :conditions => ["user_id = ? AND date_begin = ?", u.id, e.date_begin])
				if @this_user != nil
					e[:count] = e.count + @this_user.is_free
					e.save
				end
			end
		end
		
		#bunch up the time slots to form the appropriate duration
		k = @event.duration
		n = 0
		@best = Array.new
		while k>0
			k = k-30
			n = n+1
		end
		slots = @event_times.length() - n + 1
		slots.times do |i|
			beginTime = @event_times[i].date_begin
     #  beginTime.localtime
			endTime = @event_times[i+n-1].date_end
			if (endTime - beginTime) == @event.duration * 60
				minCount = @event_times[i].count
				@event_times[i,n].each do |e|
					if e.count < minCount
						minCount = e.count
					end
				end
				@best.insert(-1,EndarEventTime.new(:date_begin => beginTime, :date_end => endTime, :count => minCount))
			end
		end
		
		#sort all the appropriate durations, then choose the top 3 stored in @best
		@best = @best.sort_by {|b| b.date_begin}
		@best = @best.reverse
		@best = @best.sort_by {|b| b.count}
		@best = @best.reverse
		@best = @best[0,3]
		session[:best] = @best
		puts "BEST TIMEEEEEEEEEEEEEEEEEEEEEEEEEE"
		puts @best
	end
end

#def utc_toggle
     
    #$utc_flag = whatever
    
    #if $utc_flag == 1
     # $utc_flag = 0
    #else
      #$utc_flag = 1  
    #end   
 # return if xhr?  
  
#end
